package com.qingzhuge.common.xss;

import com.qingzhuge.exception.ValidatorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author : zero.xiao
 * @description : SQL过滤
 * @date :2018/6/14 0014 下午 17:31
 * @since : 1.0.0
 * @modified :
 */
public class SQLFilter {
    private static Logger logger = LoggerFactory.getLogger(SQLFilter.class);
    /** 判断黑名单*/
    private static String[] injStra = {"script", "mid", "master", "truncate", "insert", "select", "delete", "update", "declare",
            "iframe", "'", "onreadystatechange", "alert", "atestu", "xss", ";", "'", "\"", "<", ">", "(", ")", "\\",
            "svg", "confirm", "prompt", "onload", "onmouseover", "onfocus", "onerror"};
    /**
     * SQL注入过滤
     * @param str  待验证的字符串
     */
    public static String sqlInject(String str){
        if(StringUtils.isBlank(str)){
            return null;
        }
        //去掉'|"|;|\字符
        str = StringUtils.replace(str, "'", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");
        str = StringUtils.replace(str, "<", "");
        str = StringUtils.replace(str, ">", "");
        str = StringUtils.replace(str, "(", "");
        str = StringUtils.replace(str, ")", "");
        //转换成小写
        str = str.toLowerCase();
        //判断是否包含非法字符
        for(String keyword : injStra){
            if(str.contains(keyword)){
                throw new ValidatorException("包含非法字符");
            }
        }
        return str;
    }

    /**
     * 检查是否存在非法字符，防止SQL注入
     *
     * @param str 被检查的字符串
     * @return ture-字符串中存在非法字符，false-不存在非法字符
     */
    public static boolean checkSQLInject(String str) {
        str = str.toLowerCase();
        // sql不区分大小写
        for (String aninjStra : injStra) {
            if (str.contains(aninjStra)) {
                logger.info("传入str=" + str + ",包含特殊字符：" + aninjStra);
                return true;
            }
        }
        return false;
    }
}
